package com.alphaking.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class FileUtil {
	
	private static BASE64Decoder decoder =null;
	private static BASE64Encoder encoder =null;
	 
	 //鍒濆鍖栫紪鐮佸櫒鍜岃В鐮佸櫒
	 static{
		 decoder = new BASE64Decoder();
		 encoder = new BASE64Encoder();
	 }
	 
	 /**
	 * @param filePath 鏂囦欢鐨勮矾寰�
	 * @return  String 鏂囦欢缂栫爜鎴怋ase64String
	 * @function 鎶婃枃浠惰浆鎹㈡垚Base64String
	 */
	public static String File2String(String filePath) {//灏嗘枃浠惰浆鍖栦负瀛楄妭鏁扮粍瀛楃涓诧紝骞跺鍏惰繘琛孊ase64缂栫爜澶勭悊  
		BufferedInputStream in = null;
	        byte[] data = null;
	        //璇诲彇鏂囦欢瀛楄妭鏁扮粍  
	        try {
	            in = new BufferedInputStream(new FileInputStream(filePath));
	            
	            data = new byte[in.available()];
	            in.read(data);
	            in.close();
	        } catch (IOException e) {
	        	
	            e.printStackTrace();
	        }
	        //瀵瑰瓧鑺傛暟缁凚ase64缂栫爜  
	     
	        return encoder.encode(data);//杩斿洖Base64缂栫爜杩囩殑瀛楄妭鏁扮粍瀛楃涓� 
	    }

	    /**
	     * @param fileStr 鏂囦欢Base64 瀛楃涓�
	     * @param saveDir 鏂囦欢淇濆瓨鐩綍
	     * @param fileName 鏂囦欢鍚�
	     * @return boolean 淇濆瓨鎴愬姛涓庡惁
	     * @function 鎶夿ase64String杞崲鎴愭枃浠朵繚瀛�
	     */
	    public static boolean String2File(String fileStr, String saveDir,String fileName) {//瀵瑰瓧鑺傛暟缁勫瓧绗︿覆杩涜Base64瑙ｇ爜骞剁敓鎴愭枃浠� 
	        
	    	if (fileStr == null) //鏁版嵁涓虹┖  
	            return false;
	        
	    	String savePath = saveDir+File.separator+fileName;
	    	
	        try {
	            //Base64瑙ｇ爜  
	            byte[] b = decoder.decodeBuffer(fileStr);
	            for (int i = 0; i < b.length; ++i) {
	                if (b[i] < 0) {//璋冩暣寮傚父鏁版嵁  
	                    b[i] += 256;
	                }
	            }
	            
	            File  outFile = getOutFile(savePath);
	            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));
	            
	            out.write(b);//鍐欏埌鏂囨枃浠朵腑
	            out.flush();
	            out.close();
	            return true;
	        } catch (Exception e) {
	            return false;
	        }
	    }

	/**
	 * 
	 * @param inFile 杈撳叆鏂囦欢
	 * @param saveDir 鏂囦欢淇濆瓨鐩綍
	 * @param fileName 鏂囦欢鍚�
	 * @throws IOException
	 * @function 淇濆瓨鏅�鏂囦欢
	 */
	public static void saveFile(File inFile,String saveDir,String fileName) throws IOException{
		
		String savePath = saveDir+File.separator+fileName;
		File outFile = getOutFile(savePath);
		OutputStream out = new FileOutputStream(outFile);
		InputStream in = new FileInputStream(inFile);
		
		byte[] bytes = new byte[512];
		int len;
		
		while((len=in.read(bytes))>0){
			out.write(bytes, 0, len);
		}
		
		out.flush();
		in.close();
		out.close();
	}
	
	private static File getOutFile(String savePath){
		File file = new File(savePath);
		deleteFile(file);
		return file;
	}
	
	public static void deleteFile(File file){
		if(file.exists()){//鏄惁宸茬粡瀛樺湪
        	if(file.delete()){//鍒犻櫎鍘熸潵鐨勬枃浠�
        		System.out.println("Delete Old File:");
        	}
        }
	}
	
	/**
	 * 
	 * @param request http璇锋眰鍩�
	 * @param saveDir 鏂囦欢淇濆瓨鐩綍
	 * @param accessUrl 鏂囦欢璁块棶鍓嶇紑
	 * @return 鍙闂殑鏂囦欢URL鐨勯泦鍚�
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public static List<String> springMvcUpload(HttpServletRequest request,String saveDir,String accessUrl)
			throws IllegalStateException, IOException {
		HttpSession session = request.getSession();
		List<String> saveUrl = new ArrayList<String>();
		// 鍒涘缓涓�釜閫氱敤鐨勫閮ㄥ垎瑙ｆ瀽鍣�
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				session.getServletContext());
		int i = 0;
		// 鍒ゆ柇 request 鏄惁鏈夋枃浠朵笂浼�鍗冲閮ㄥ垎璇锋眰
		System.out.println("----准备进来了----");
		if (multipartResolver.isMultipart(request)) {
			System.out.println("----进来了----");
			// 杞崲鎴愬閮ㄥ垎request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 鍙栧緱request涓殑鎵�湁鏂囦欢鍚�
			Iterator<String> iter = multiRequest.getFileNames();

			while (iter.hasNext()) {
				System.out.println("----再进一步----");
				// 璁板綍涓婁紶杩囩▼璧峰鏃剁殑鏃堕棿锛岀敤鏉ヨ绠椾笂浼犳椂闂�
				int pre = (int) System.currentTimeMillis();
				// 鍙栧緱涓婁紶鏂囦欢
				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null) {
					// 鍙栧緱褰撳墠涓婁紶鏂囦欢鐨勬枃浠跺悕绉�
					String myFileName = file.getOriginalFilename();
					if (myFileName != null && !myFileName.trim().equals("")) {
						// 鑾峰彇鏂囦欢鍚庣紑鍚�
						String ext = myFileName.substring(myFileName.lastIndexOf("."));
						// 閲嶅懡鍚嶄笂浼犲悗鐨勬枃浠跺悕
						String fileName = System.currentTimeMillis() + "" + i+ ext;
						// 瀹氫箟涓婁紶璺緞
						String savePath = saveDir + fileName;
						File localFile = new File(savePath);
						file.transferTo(localFile);
//						saveUrl.add(accessUrl + fileName);
						saveUrl.add(accessUrl+fileName);
						System.out.println("--------------------------------");
						System.out.println("鍘熷鏂囦欢鍚�-" + myFileName);
						System.out.println("鏂版枃浠跺悕--" + fileName);
					}
				}
				// 璁板綍涓婁紶璇ユ枃浠跺悗鐨勬椂闂�
				int finaltime = (int) System.currentTimeMillis();
				System.out.println("涓婁紶鐢ㄦ椂--"+(finaltime - pre));
				System.out.println("--------------------------------");
				i++;
			}
		}
		return saveUrl;
	}

	/**
	 * 
	 * @param response http鍝嶅簲澶�
	 * @param filePath 寰呬笅杞界殑鏂囦欢璺緞
	 */
	public static void downLoad(HttpServletResponse response, String filePath) {
		File file = new File(filePath);
		FileInputStream input = null;
		OutputStream output = null;
//		response.setContentType("text/html;charset =utf-8");
		response.setContentType("octets/stream");
		try {
			response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
			//瑙ｅ喅鏄剧ず娴忚鍣ㄧ殑涓嬭浇绐楀彛涔辩爜闂
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		byte[] buffer = new byte[1024];
		try {
			input = new FileInputStream(file);
			output = response.getOutputStream();
			int len = 0;
			while ((len = input.read(buffer, 0, buffer.length)) != -1) {
				output.write(buffer, 0, len);
			}
			output.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (output != null) {
					output.close();
					output = null;
				}
				if (input != null) {
					input.close();
					input = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}
	
	
	/**
	  * 将图片写入到磁盘
	  * @param img 图片数据流
	  * @param fileName 文件保存时的名称
	  */
	 public static void byteArrayToDisk(byte[] img, String fileName, String path){
		 try {
			 File file = new File(path + fileName);
			 FileOutputStream fops = new FileOutputStream(file);
			 fops.write(img);
			 fops.flush();
			 fops.close();
		 } catch (Exception e) {
			 e.printStackTrace();
		 }
	 }
	
}
